/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pfc.generacion;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import pfc.arbol.ApplicationTreeNode;
import pfc.arbol.FolderTreeNode;
import pfc.arbol.ProyectoTreeNode;
import pfc.comun.IDEpfc;
import pfc.comun.Proyecto;

/**
 *
 * @author xandru
 */
public class ApplicationManager {

    ProyectoTreeNode _node;
    Proyecto _proyecto;
    ArrayList<Application> _apps = new ArrayList<Application>();

    public ApplicationManager(ProyectoTreeNode aThis, Proyecto proyecto) {
        this._node = aThis;
        this._proyecto = proyecto;
    }

    public Application newApplication(int numero) {
        File f = new File(_proyecto.getAppsFolder() + File.separator + "Aplicacion" + numero);
        try {
            FileUtils.forceMkdir(f);
        } catch (IOException ex) {
            Logger.getLogger(ApplicationManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        Application app = new Application(f);
        _apps.add(app);
        return app;
    }

    public void deleteApplication(ApplicationTreeNode aThis) {
        String app = aThis.getNombre();
        Application aBorrar = null;
        for (Application p: this._apps)
        {
            if (p.getName().equals(app))
            {
                aBorrar = p;
                break;
            }
        }

        if (aBorrar!=null)
        {
             FolderTreeNode f = (FolderTreeNode) aThis.getParent();
             f.remove(aThis);
             IDEpfc.refreshTree(f);
        }
        try {
            FileUtils.deleteDirectory(new File(this._proyecto.getAppsFolder() + File.separator + app));
        } catch (IOException ex) {
            Logger.getLogger(ApplicationManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void addApplication(Application application) {
        this._apps.add(application);
    }

    public Application getApplication(String name)
    {
        for (Application a:this._apps)
        {
            if (StringUtils.equals(a.getName(), name))
              return a;
        }
        return null;
    }

}
